-
Notifications
You must be signed in to change notification settings - Fork 99
Git homework #128
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Git homework #128
Conversation
Krabler228
commented
Aug 25, 2025
- Нашел конфликт
- Исправил конфликт
- Прогнал через линтер
- дикий огурец
…асписал все ответы в файле readme
|
|
||
| jobs: | ||
| ruff: | ||
| runs-on: ubuntu-latest |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
latest образ кринж юзать, используй конкретную версию и по возможности слим
| python-version: "3.11" | ||
|
|
||
| - name: Install Ruff | ||
| run: pip install ruff |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
тут лучше тоже конкретную версию ставить + закэшировать можно установку
| try: | ||
| return json.load(file) | ||
| except json.JSONDecodeError: | ||
| return [] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
try except можно в такой ситуации не юзать, а просто на самый верх прокидывать ошибку и если че в fastapi exception handler ловить исключения
| from settings import JSONBIN_API_KEY, JSONBIN_BIN_ID, CF_API_TOKEN, CF_ACCOUNT_ID, CF_MODEL | ||
|
|
||
| JSONBIN_BASE = "https://api.jsonbin.io/v3/b" | ||
| CF_BASE = "https://api.cloudflare.com/client/v4" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
переменные с url лучше тянуть из env через pydanric base settings или starlette и хранить в отдельном файле с конфигом
| self.path = Path(path) | ||
| if not self.path.exists(): | ||
| self.save([]) | ||
| def load(self) -> list[dict]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
у дикта можно типы внутренностей указать. а ещё лучше юзать pydantic модели вместо дикта
| r.raise_for_status() | ||
| return r.json()["record"] | ||
| def save(self, data: list[dict]) -> None: | ||
| r = requests.put(f"{JSONBIN_BASE}/{self.bin_id}", headers=self.headers, json=data, timeout=10) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
длиннющая строка, можно url в отдельную переменную выше записать
| def __init__(self): | ||
| self.url = f"{CF_BASE}/accounts/{CF_ACCOUNT_ID}/ai/run/{CF_MODEL}" | ||
| self.headers = {"Authorization": f"Bearer {CF_API_TOKEN}"} | ||
| def explain(self, text: str) -> str: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ты мог сделать методы post, get и тд вместо explain, save и тд, и вынести их в общий родительский класс
| def get_tasks() -> list[dict]: | ||
| return storage.load() | ||
|
|
||
| @app.post("/tasks") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
нужно указывать response_model= и это должна быть pydantic модель
| def to_dict(self): | ||
| return {"task_id": self.task_id, "name": self.name, "status": self.status} | ||
|
|
||
| @app.get("/tasks") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
коннекти эндпоинты к роутеру , а не к приложению фастапи
| - отваливаются данные при перезапуске | ||
| Хранение в json | ||
| + задачи сохраняются на диск и не пропадают | ||
| - все еще stateful плюс проблемы с одновременным сохранением и тд |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
не stateful. когда состояние хранится во внешнем хранилище, это уже стейтлесс
|
|
||
| JSONBIN_API_KEY = os.getenv("JSONBIN_API_KEY") | ||
| JSONBIN_BIN_ID = os.getenv("JSONBIN_BIN_ID") | ||
| CF_API_TOKEN = os.getenv("CF_API_TOKEN") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
нормас, но можно юзать starlette config либо pydantic base settings, так чище и моднее
| JSONBIN_BIN_ID = os.getenv("JSONBIN_BIN_ID") | ||
| CF_API_TOKEN = os.getenv("CF_API_TOKEN") | ||
| CF_ACCOUNT_ID = os.getenv("CF_ACCOUNT_ID") | ||
| CF_MODEL = os.getenv("CF_MODEL", "@cf/meta/llama-3.1-8b-instruct") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
можно файл .env.example ещё пушить с пустыми переменными
| Хранени | ||
| Состояние гонки | ||
| Это ситуация, когда два клиента одновременно читают старое состояние и перезаписывают друг друга. - это термин из интернета | ||
| Как я понял: состояние гонки это когда один файл берут два человека и пытаются с ним работать(не получится - файл то один). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
получится, но там данные могут быть записаны не в том порядке либо какие-то могут отсутствовать либо несогласованно
LilChichaaa
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
поправить наследование